var React = require('react');

var ListHeader = require('../widget/ListHeader');
var ListItem = require('../widget/ListItem');
var ajax = require('../tools/ajax');
var Icon = require('../components/Icon');
var MsgBox = require('../components/MsgBox');

module.exports = React.createClass({
    getInitialState: function () {
        return {
            shopId:"",//店铺ID
            cartProList:"",//店铺下的购物车商品
            cartList:[],
            shopChecked:{},//选中店铺
            goodsChecked:{},//选中商品
            numGoods:{},//商品数量
            goodsPrice:{},//商品单价
            oneTotalPrice:{},//单个商品总金额集
            ckFlag:false,//单个商品选择判断
            checked :"false",
            totalPrice:0,//全部总金额
            ckPrice:[],//选中商品的价格
            goodsIDList:[],//选中的商品goods_id
            checkAll:0,
            totalNum:0,//选中商品数量
            wxy:'',
            bianjiFlag:false,
            cartNum:null,
            first:true,
        }
    },

    componentDidMount: function () {
        var p=this;
        setTimeout(p.attr,200);
        setTimeout(p.getCartByShopid,500);
        //setTimeout(this.leftDelete,500);

    },
    attr(){
        if(this.props.shopId){
            this.setState({shopId:this.props.shopId});
        }
    },
    ///**侧滑显示删除按钮*/
    //leftDelete(){
    //    //侧滑显示删除按钮
    //    var expansion = null; //是否存在展开的list
    //    var container = this.refs.cartListItem;
    //    if(container) {
    //        for (var i = 0; i < container.length; i++) {
    //            var x, y, X, Y, swipeX, swipeY;
    //            container[i].addEventListener('touchstart', function (event) {
    //                x = event.changedTouches[0].pageX;
    //                y = event.changedTouches[0].pageY;
    //                swipeX = true;
    //                swipeY = true;
    //                if (expansion) {   //判断是否展开，如果展开则收起
    //                    expansion.className = "";
    //                }
    //            });
    //            container[i].addEventListener('touchmove', function (event) {
    //                X = event.changedTouches[0].pageX;
    //                Y = event.changedTouches[0].pageY;
    //                // 左右滑动
    //                if (swipeX && Math.abs(X - x) - Math.abs(Y - y) > 0) {
    //                    // 阻止事件冒泡
    //                    event.stopPropagation();
    //                    if (X - x > 10) {   //右滑
    //                        event.preventDefault();
    //                        this.className = "cartListItem";    //右滑收起
    //                    }
    //                    if (x - X > 10) {   //左滑
    //                        event.preventDefault();
    //                        this.className = "cartListItem swipeleft";//左滑展开
    //                        expansion = container[i];
    //                    }
    //                    swipeY = false;
    //                }
    //                // 上下滑动
    //                if (swipeY && Math.abs(X - x) - Math.abs(Y - y) < 0) {
    //                    swipeX = false;
    //                }
    //            });
    //        }
    //    }
    //},
    /**根据店铺获取购物车信息*/
    getCartByShopid(){
        var p =this;
        var shop_id = p.state.shopId;
        var userId = localStorage.getItem("userId");
        var first = p.state.first;
        ajax("POST","getCartByShopid",{user_id:userId,shop_id:shop_id},function(dt){
            if(dt&&dt.success){
                var objs = dt.data;
                p.setState({cartList:objs},()=>{
                    if(first){
                        p.init();
                    }
                });
            }
        });
        p.setState({first:false});
    },
    /**数据初始化*/
    init(){
        var p =this;
        var shop_id = p.state.shopId;
        var cartList = p.state.cartList;
        var oneTotalPrice = {},
            goodsChecked ={},
            numGoods = {},
            shopChecked = {},
            goodsPrice = {},
            cartNum = {};
        shopChecked[shop_id] = false;
        cartNum[shop_id] = cartList.length;
        for(var i = 0; i < cartList.length; i++){
            var sg = shop_id+cartList[i].goods_id;
            numGoods[sg] = cartList[i].goods_number;
            oneTotalPrice[sg] = parseFloat(cartList[i].goods_number*cartList[i].goods_price).toFixed(2);
            goodsChecked[sg] = false;
            goodsPrice[sg] = cartList[i].goods_price;
        }
        p.setState({
            oneTotalPrice:oneTotalPrice,
            goodsChecked:goodsChecked,
            numGoods:numGoods,
            shopChecked:shopChecked,
            cartNum:cartNum
        });
    },
    /**单选*/
    change:function(e){
        var p=this;
        var shopId = e.currentTarget.getAttribute('data-shopid');
        shopId = shopId != null ? shopId:"";
        var goods_id = e.currentTarget.getAttribute('data-id');
        var sg = shopId + goods_id;
        var goodsChecked = p.state.goodsChecked;
        var oneTotalPrice = p.state.oneTotalPrice;
        var shopChecked = p.state.shopChecked;
        var totalPrice = p.state.totalPrice;
        goodsChecked[sg] = !goodsChecked[sg];
        if(goodsChecked[sg]){
            totalPrice = (parseFloat(totalPrice*100 + oneTotalPrice[sg]*100)/100).toFixed(2);
        }else{
            totalPrice = (parseFloat(totalPrice*100 - oneTotalPrice[sg]*100)/100).toFixed(2);
        }
        var flag = false;
        for(var i in goodsChecked){
            if(goodsChecked[i]){
                flag = true;
            }else{
                flag = false;
                break;
            }
        }
        shopChecked[shopId] = flag;
        p.setState({
            goodsChecked:goodsChecked,
            shopChecked:shopChecked,
            totalPrice:totalPrice
        },()=>{
            p.props.allTotal();
            p.props.sc(shopId); 
        });
    },
    /**增加商品数量*/
    increaseNum:function(e){
        var p =this;
        var userId = localStorage.getItem('userId');
        var goods_id = e.currentTarget.getAttribute('data-id');
        var shopId = e.currentTarget.getAttribute('data-shopid');
        var sg = shopId+goods_id;
        var price = e.currentTarget.getAttribute('data-price');
        var good_num = e.currentTarget.getAttribute('data-num');
        var stock = e.currentTarget.getAttribute('data-stock');//库存
        if(parseInt(good_num) < parseInt(stock)){
            good_num = parseInt(good_num) + 1;
            console.log(good_num);
            var numGoods = p.state.numGoods;
            numGoods[sg] = good_num;
            p.setState({numGoods:numGoods});
            var onePrice = good_num*price;
            var oneTotalPrice = p.state.oneTotalPrice;
            var totalPrice = p.state.totalPrice;
            oneTotalPrice[sg] = parseFloat(onePrice).toFixed(2);
            //计算总价格
            if(p.state.goodsChecked[sg]) {
                totalPrice = (parseFloat(totalPrice*100 + price*100)/100).toFixed(2);
            }
            p.setState({
                oneTotalPrice:oneTotalPrice,
                totalPrice:totalPrice
            },()=>{
                p.props.allTotal();
            });
            ajax("POST","updateGoodsnum",{
                user_id:userId,
                goods_id:goods_id,
                num:"1",
                shopId:shopId,
            },function(dt){
                if(dt && dt.success){
                    p.getCartByShopid();
                    console.log("更新成功");
                }
            });
        }
    },
    /**减去商品数量*/
    reduceNum:function(e){
        var p =this;
        var shopId = e.currentTarget.getAttribute('data-shopid');
        var goods_id = e.currentTarget.getAttribute('data-id');
        var sg = shopId+goods_id;
        var stock = e.currentTarget.getAttribute('data-stock');//库存
        var userId = localStorage.getItem('userId');
        var good_num = e.currentTarget.getAttribute('data-num');
        var price = e.currentTarget.getAttribute('data-price');
        if(parseInt(good_num) != 1){
            good_num = parseInt(good_num) - 1;
            console.log(good_num);
            var numGoods = p.state.numGoods;
            numGoods[sg] = good_num;
            p.setState({numGoods:numGoods});
            //计算单个价格
            var onePrice = good_num*price;
            var oneTotalPrice = p.state.oneTotalPrice;
            var totalPrice = p.state.totalPrice;
            oneTotalPrice[sg] = parseFloat(onePrice).toFixed(2);
            this.setState({oneTotalPrice:oneTotalPrice});
            //计算总价格
            if(p.state.goodsChecked[sg]){
                totalPrice = (totalPrice*100 - price*100)/100;
            }
            p.setState({
                oneTotalPrice:oneTotalPrice,
                totalPrice:totalPrice
            },()=>{
                p.props.allTotal();
            });
            ajax("POST","updateGoodsnum",{
                user_id:userId,
                goods_id:goods_id,
                shopId:shopId,
                num:"-1"
            },function(dt){
                if(dt && dt.success){
                    p.getCartByShopid();
                    console.log("更新成功");
                }
            });
        }
    },
    render: function () {
        var p = this;
        var cartProList = p.state.cartList.map(function(obj,index){
            if(obj.goods_img){
                var goods_img = obj.goods_img.split(",")[0];
            }
            var sg = obj.shop_id + obj.goods_id;
            return(
                <li key={index} className="cartListWrap">
                    <div className="cartListItem">
                        <div className="cartProInfo">
                            <div className={p.state.shopChecked[obj.shop_id]?"cartIcon checked":(p.state.goodsChecked[sg]?"cartIcon checked":"cartIcon")} onClick={p.change} data-shopid={obj.shop_id} data-id={obj.goods_id}>
                                <Icon icon="#icon-xuanzhong1"></Icon>
                            </div>
                            <img src={goods_img}/>
                            <div className="des">
                                <p>{obj.goods_name}</p>
                                <div className="num">
                                    <div className="reduce btn" onClick={obj.is_discount!=1 ? p.reduceNum:p.props.msg}  data-index={index} data-num={p.state.numGoods[sg]} data-shopid={obj.shop_id} data-id={obj.goods_id} data-price={obj.goods_price}>
                                        <Icon icon="#icon-jianshao" />
                                    </div>
                                    <p className="number">{p.state.numGoods[sg]}</p>
                                    <div className="push btn" onClick={obj.is_discount!=1 ? p.increaseNum:p.props.msg}   data-stock={obj.stock}  data-num={p.state.numGoods[sg]} data-shopid={obj.shop_id} data-id={obj.goods_id} data-price={obj.goods_price}>
                                        <Icon icon="#icon-tianjia1" />
                                    </div>
                                    <div className="price">
                                        ¥<span>{p.state.oneTotalPrice[obj.shop_id+obj.goods_id]}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="delete" onClick={p.deleteCartProByGoodsId} data-shopid={obj.shop_id} data={obj.goods_id}>删除</div>
                    </div>
                    <hr className="cart_hr"/>
                </li>
            )
        });
        return (
            <ul className="cartWrap">
                {cartProList}
            </ul>
        )
    }
});
